// pages/fahua/fahua.js
// 日期
const app = getApp();

const date = new Date()
const years = []
const months = []
const days = []

for (let i = 1990; i <= date.getFullYear() + 1; i++) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  months.push(i)
}

for (let i = 1; i <= 31; i++) {
  days.push(i)
}



Page({
  /**
   * 页面的初始数据
   */ 
  data: {
    huoindex: 1,
    diquList: [], //地区列表
    nowpage: 1, //当前页数
    sumpage: 1, //总页数
    townid: '',


    select: false, //项目选项
    tihuoWay: '按商品排序', //默认选项
    regionanamelist: [], //区域列表只有名字和ID
    regionalnum: 0, //地区的个数
    selectregionainfo: {},
    siteindexs: 0, //默认0未选择任何地址



    years: years, //日期初始化
    months: months,
    days: days,
    value1: [],
    value2: [],
    year2: '',
    year3: '',
    month2: '',
    month3: '',
    day2: '',
    day3: '',
    showAnceng: false, //暗层
    goodsModalone: false, //商品统计选择开始时间弹窗
    goodsModaltwo: false, //商品统计选择结束时间弹窗
    siteAnceng: false, //暗层
    siteModal: false, //选择地区时间弹窗
    goodsModaltwo: false, //商品统计选择结束时间弹窗
    zanshistartTime: '', //点击下一步时暂时存储的时间
    dingdanTimes2: ''
  },
  // 弹出下拉
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  // 选择区域
  fixdiqu(e) {
    let that = this
    console.log(e.currentTarget.dataset.index)
    that.setData({
      siteindexs: e.currentTarget.dataset.index
    })
  },
  // 取消
  quxiao() {
    let that = this
    let regionanamelist = that.data.regionanamelist
    if (!that.data.selectregionainfo.townId) {
      let selectregionainfo = {}
      if (regionanamelist.length > 0) {
        selectregionainfo = regionanamelist[0]
      }
      that.setData({
        siteModal: false,
        siteAnceng: false,
        selectregionainfo: selectregionainfo
      })
      that.getqingdan()
    } else {
      this.setData({
        siteModal: false,
        siteAnceng: false
      })
    }
  },
  // 确定
  queding() {
    let that = this
    let regionanamelist = that.data.regionanamelist
    if (!that.data.siteindexs) {
      setTimeout(function() {
        wx.showToast({
          title: '请选择区域',
          icon: 'none'
        })
      }, 0)
      return
    }
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
      })
    }, 0)
    that.setData({
      siteModal: false,
      siteAnceng: false,
      selectregionainfo: regionanamelist[that.data.siteindexs - 1],
      diquList: [],
      nowpage: 1,
      sumpage: 1,
    })
    that.getqingdan()
  },








  // 获取所有区域
  shippingArea() {
    let that = this
    let timesobj = that.data.dingdanTimes2
    let star, end
    if (that.data.huoindex == 1) {
      star = ''
      end = ''
    } else {
      star = timesobj.yearstar + '-' + timesobj.monthstar + '-' + timesobj.daystar + ' 00:00:00'
      end = timesobj.yearend + '-' + timesobj.monthend + '-' + timesobj.dayend + ' 23:59:59'
    }
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "shippingArea",
        shopId: wx.getStorageSync('shopId'),
        userId: wx.getStorageSync('userId'),
        type: that.data.huoindex,
        beginAdtime: star,
        endAdtime: end
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }else{
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res, 7788)
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          // that.setData({
          //   regionanamelist: res.data.areaList,
          //   regionalnum: res.data.areaList.length
          // })
          if (res.data.areaList.length == 0) {
            setTimeout(function () {
              wx.hideLoading()
            }, 0)
            setTimeout(function () {
              wx.showToast({
                title: '您当前没有相关订单，不可选择地区',
                icon: 'none',
              })
            }, 0)
            that.setData({
              siteindexs: 0,
            })
            that.setData({
              regionanamelist: res.data.areaList,
              regionalnum: res.data.areaList.length
            })
          } else {
            that.setData({
              siteModal: true,
              siteAnceng: true,
              siteindexs: 0,
            })
            that.setData({
              regionanamelist: res.data.areaList,
              regionalnum: res.data.areaList.length
            })
            setTimeout(function() {
              wx.hideLoading()
            }, 0)
          }


        }
      }
    });
  },
  //订单详情
  toddxq(e) {
    // console.log(e)
    let type = e.currentTarget.dataset.ordertype
    let dingdanId = e.currentTarget.dataset.dingdanid

    wx.navigateTo({
        url: '/pages/order/page/chuantongDingdan/dingdanXqwu/dingdanXqwu?dingdanId=' + dingdanId,
      })


    // if (type == 1) {
    //   wx.navigateTo({
    //     url: '/pages/order/page/chuantongDingdan/dingdanXqwu/dingdanXqwu?dingdanId=' + dingdanId,
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/order/page/daixiaoDingdan/shenheAndfahuo/shenheAndfahuo?dingdanId=' + dingdanId,
    //   })
    // }
  },
  // 商品统计统计开始时间
  tongJiStart1(e) {
    console.log(e)
    let that = this
    let value1 = that.data.value1
    let value2 = that.data.value2
    value1[0] = e.currentTarget.dataset.timeobj.yearstar * 1 - 1990
    value1[1] = e.currentTarget.dataset.timeobj.monthstar * 1 - 1
    value1[2] = e.currentTarget.dataset.timeobj.daystar * 1 - 1
    value2[0] = e.currentTarget.dataset.timeobj.yearend * 1 - 1990
    value2[1] = e.currentTarget.dataset.timeobj.monthend * 1 - 1
    value2[2] = e.currentTarget.dataset.timeobj.dayend * 1 - 1
    that.setData({
      goodsModalone: true,
      showAnceng: true,
      zanshistartTime: '',
      value1: value1,
      value2: value2,
      year2: e.currentTarget.dataset.timeobj.yearstar,
      year3: e.currentTarget.dataset.timeobj.yearend,
      month2: e.currentTarget.dataset.timeobj.monthstar,
      month3: e.currentTarget.dataset.timeobj.monthend,
      day2: e.currentTarget.dataset.timeobj.daystar,
      day3: e.currentTarget.dataset.timeobj.dayend,
    })
  },
  // 订单日期切换
  dingdanChange2: function(e) {
    const val = e.detail.value
    this.setData({
      year2: this.data.years[val[0]],
      month2: this.data.months[val[1]],
      day2: this.data.days[val[2]]
    })
  },
  // 订单日期切换
  dingdanChange3: function(e) {
    const val = e.detail.value
    this.setData({
      year3: this.data.years[val[0]],
      month3: this.data.months[val[1]],
      day3: this.data.days[val[2]]
    })
  },
  // 统计下一步时间
  xiayiBu: function() {
    let that = this
    let times = {}
    times.year = that.data.year2
    if (that.data.month2 * 1 < 10) {
      times.month = '0' + that.data.month2 * 1
    } else {
      times.month = that.data.month2
    }
    if (that.data.day2 * 1 < 10) {
      times.day = '0' + that.data.day2 * 1
    } else {
      times.day = that.data.day2
    }
    this.setData({
      goodsModalone: false,
      goodsModaltwo: true,
      zanshistartTime: times
    })
  },
  // 统计确定时间
  quedingEnd: function() {
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0)
    let that = this
    let times = {}
    let zanshistartTime = that.data.zanshistartTime
    let dingdanTimes2 = that.data.dingdanTimes2
    times.year = that.data.year3
    if (that.data.month3 * 1 < 10) {
      times.month = '0' + that.data.month3 * 1
    } else {
      times.month = that.data.month3 * 1
    }
    if (that.data.day3 * 1 < 10) {
      times.day = '0' + that.data.day3 * 1
    } else {
      times.day = that.data.day3 * 1
    }
    dingdanTimes2.yearstar = zanshistartTime.year
    dingdanTimes2.monthstar = zanshistartTime.month
    dingdanTimes2.daystar = zanshistartTime.day
    dingdanTimes2.yearend = times.year
    dingdanTimes2.monthend = times.month
    dingdanTimes2.dayend = times.day
    this.setData({
      showAnceng: false,
      goodsModaltwo: false,
      dingdanTimes2: dingdanTimes2,
      diquList: [],
      nowpage: 1,
      sumpage: 1,
    })
    that.getqingdan()
  },
  // 关闭订单日期弹窗
  close_dingdanTime: function() {
    this.setData({
      showAnceng: false, //暗层的显示
      goodsModalone: false, //商品统计选择开始时间弹窗
      goodsModaltwo: false, //商品统计选择结束时间弹窗
    })

  },
  // 选定区域后多选订单
  duoxuan(e) {
    console.log('一键发货')
    let that = this
    let list = that.data.diquList
    for (var i in list) {
      list[i].fahuoflag = false
    }
    list[e.currentTarget.dataset.quyuindex].fahuoflag = true
    for (var i in list[e.currentTarget.dataset.quyuindex].orderBeans) {
      list[e.currentTarget.dataset.quyuindex].orderBeans[i].fixflag = false
    }
    that.setData({
      diquList: list,
      townid: list[e.currentTarget.dataset.quyuindex].townId
    })
  },
  //多选取消
  duoxuanqx(e) {
    let that = this
    let list = that.data.diquList
    for (var i in list) {
      list[i].fahuoflag = false
      list[i].quanxuan = false
    }
    that.setData({
      diquList: list,
      townid: ''
    })
  },
  // 全选按钮
  fixquanxuan(e) {
    let that = this
    let list = that.data.diquList
    list[e.currentTarget.dataset.quyuindex].quanxuan = !list[e.currentTarget.dataset.quyuindex].quanxuan
    for (var i in list[e.currentTarget.dataset.quyuindex].orderBeans) {
      list[e.currentTarget.dataset.quyuindex].orderBeans[i].fixflag = list[e.currentTarget.dataset.quyuindex].quanxuan
    }
    that.setData({
      diquList: list
    })
  },
  // 单选按钮
  danxuan(e) {
    let that = this
    let list = that.data.diquList
    list[e.currentTarget.dataset.quyuindex].orderBeans[e.currentTarget.dataset.dingdanindex].fixflag = !list[e.currentTarget.dataset.quyuindex].orderBeans[e.currentTarget.dataset.dingdanindex].fixflag
    let flag = true
    for (var i in list[e.currentTarget.dataset.quyuindex].orderBeans) {
      if (!list[e.currentTarget.dataset.quyuindex].orderBeans[i].fixflag) {
        flag = false
      }
    }
    list[e.currentTarget.dataset.quyuindex].quanxuan = flag
    that.setData({
      diquList: list
    })
  },
  // 多选发货
  duoxuanfh(e) {
    let that = this
    let list = that.data.diquList[e.currentTarget.dataset.quyuindex].orderBeans
    let orderList = []
    for (var i in list) {
      if (list[i].fixflag) {
        orderList.push(list[i].id)
      }
    }
    if (orderList.length < 1) {
      setTimeout(function() {
        wx.showToast({
          title: '至少选择一个订单',
          icon: 'none'
        })
      }, 0)
      return
    }
    wx.navigateTo({
      url: '/pages/order/page/yijianfahuo/yijianfahuo?orderList=' + JSON.stringify(orderList) + '&townid=' + that.data.townid
    })
  },

  // 获取发货列表
  getqingdan() {
    let that = this
    let timesobj = that.data.dingdanTimes2
    let star, end
    if (that.data.huoindex == 1) {
      star = ''
      end = ''
    } else {
      star = timesobj.yearstar + '-' + timesobj.monthstar + '-' + timesobj.daystar + ' 00:00:00'
      end = timesobj.yearend + '-' + timesobj.monthend + '-' + timesobj.dayend + ' 23:59:59'
    }
    let recetownId
    if (that.data.selectregionainfo.townId) {
      recetownId = that.data.selectregionainfo.townId
    } else {
      recetownId = ''
    }
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "getShippedList",
        shopId: wx.getStorageSync('shopId'),
        userId: wx.getStorageSync('userId'),
        nowPage: that.data.nowpage,
        type: that.data.huoindex,
        beginAdtime: star,
        endAdtime: end,
        recetownId: recetownId
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
          if (that.data.nowpage != 1) {
            that.setData({
              nowpage: that.data.nowpage - 1
            })
          }
        } else {
          if (that.data.nowpage == 1) {
            let list = res.data.beans
            if (list.length == 0) {
              setTimeout(function() {
                wx.hideLoading()
              }, 0)
              setTimeout(function() {
                wx.showToast({
                  title: '暂时无任何订单，请修改地区、时间试试',
                  icon: 'none',
                  duration: 1500
                })
              }, 0)
              return
            }
            for (var k in list) {
              list[k].fahuoflag = false
              let dingdanList = list[k].orderBeans
              for (var i in dingdanList) {
                // 有问题订单，会报错
                if (that.data.huoindex == 1) {
                  dingdanList[i].orederfound = dingdanList[i].orderAdtime.substring(5, 16)
                } else {
                  dingdanList[i].orederfound = dingdanList[i].orderAdtime.substring(0, 16)
                }
                let goodsList = dingdanList[i].goodsList
                for (var j in goodsList) {
                  if (goodsList[j].goodsType == 4 || goodsList[j].goodsType == 5) {
                    if (goodsList[j].actdesc && goodsList[j].freeprice) {
                      dingdanList[i].actdesc = goodsList[j].actdesc
                      dingdanList[i].freeprice = goodsList[j].freeprice
                      dingdanList[i].goodsType = goodsList[j].goodsType
                    }
                  }
                }
              }
            }
            that.setData({
              diquList: list,
              sumpage: res.data.totalPage
            })
          } else {
            let oldlist = that.data.diquList
            let list = res.data.beans
            for (var k in list) {
              list[k].fahuoflag = false
              let dingdanList = list[k].orderBeans
              for (var i in dingdanList) {
                // 有问题订单，会报错
                if (that.data.huoindex == 1) {
                  dingdanList[i].orederfound = dingdanList[i].orderAdtime.substring(5, 16)
                } else {
                  dingdanList[i].orederfound = dingdanList[i].orderAdtime.substring(0, 16)
                }
                let goodsList = dingdanList[i].goodsList
                for (var j in goodsList) {
                  if (goodsList[j].goodsType == 4 || goodsList[j].goodsType == 5) {
                    if (goodsList[j].actdesc && goodsList[j].freeprice) {
                      dingdanList[i].actdesc = goodsList[j].actdesc
                      dingdanList[i].freeprice = goodsList[j].freeprice
                      dingdanList[i].goodsType = goodsList[j].goodsType
                    }
                  }
                }
              }
              oldlist.push(list[k])
            }
            that.setData({
              diquList: oldlist,
              sumpage: res.data.totalPage
            })
          }
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
        }
      },
      fail(err) {
        setTimeout(function () {
          wx.hideLoading()
          wx.stopPullDownRefresh() //停止下拉刷新
        }, 0)
        setTimeout(function () {
          wx.showToast({
            title: '网络错误，稍后重试',
            icon: 'none',
            duration: 1500
          })
        }, 0)
      }
    });
  },
  // 去选择筛选地区
  tofixquyu() {
    let that = this
    // that.setData({
    //   siteAnceng: true,
    //   siteModal: true
    // })
    setTimeout(function() {
      wx.showLoading({
        title: '加载中'
      })
    }, 0);
    that.shippingArea()
  },
  // 去发货清单
  shippinglist() {
    let that = this
    let flag
    if (that.data.tihuoWay == '按地区排序') {
      flag = false
    } else {
      flag = true
    }
    wx.navigateTo({
      url: '/pages/order/page/fahuoqingdan/fahuoqingdan?type=' + that.data.huoindex + '&selectregionainfo=' + JSON.stringify(that.data.selectregionainfo) + '&dingdanTimes2=' + JSON.stringify(that.data.dingdanTimes2) + '&flag=' + flag
    })
  },
  // 查看物流
  toWuliu(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/setting/page/wuliuXinxi/wuliuXinxi?id=' + e.currentTarget.dataset.dingdanid,
    })
  },
  // 单个去发货
  tofahuo(e) {
    let that = this
    let list = that.data.diquList
    wx.navigateTo({
      url: '/pages/order/page/qufahuo/qufahuo/qufahuo?id=' + list[e.currentTarget.dataset.quyuindex].orderBeans[e.currentTarget.dataset.dingdanindex].id,
    })
  },
  // 切换头部
  changeshuo(e) {
    let that = this
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0);
    let indexs = e.currentTarget.dataset.index
    that.setData({
      huoindex: indexs,
      diquList: [],
      nowpage: 1,
      sumpage: 1,
      selectregionainfo: {},
      tihuoWay: '按商品排序',
      siteindexs: 0,
      select: false,
      regionanamelist: []
    })
    that.getqingdan()
  },
  // 切换排序
  changepaixu() {
    let that = this
    that.setData({
      select: !that.data.select
    })
  },
  // 选择下拉值
  mySelect(e) {
    let that = this
    var name = e.currentTarget.dataset.name
    that.setData({
      tihuoWay: name,
      select: false
    })
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0);
    if (e.currentTarget.dataset.name == '按地区排序') {
      that.setData({
        siteindexs: 0,
        selectregionainfo: {}
      })
      that.shippingArea()
    } else {
      that.setData({
        selectregionainfo: {}
      })
      that.getqingdan()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    let dates = new Date()
    let month, day
    if (dates.getMonth() + 1 < 10) {
      month = '0' + (dates.getMonth() + 1)
    } else {
      month = dates.getMonth() + 1
    }
    if (dates.getDate() < 10) {
      day = '0' + dates.getDate()
    } else {
      day = dates.getDate()
    }
    that.setData({
      year: dates.getFullYear(),
      month: month,
      day: day,
      dingdanTimes2: {
        yearstar: dates.getFullYear(),
        monthstar: month,
        daystar: '01',
        yearend: dates.getFullYear(),
        monthend: month,
        dayend: day,
      }, //选择后的商品统计日期
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
    }, 0);
    that.setData({
      diquList: [],
      nowpage: 1,
      sumpage: 1,
    })
    that.getqingdan()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    // let that = this
    // wx.showNavigationBarLoading() //在标题栏中显示加载
    // console.log('下拉舒心')
    // setTimeout(function () {
    //   wx.hideNavigationBarLoading() //完成停止加载
    //   wx.stopPullDownRefresh() //停止下拉刷新
    // }, 500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this
    let nowpage = that.data.nowpage
    nowpage = nowpage + 1
    let sumpage = that.data.sumpage
    if (nowpage <= sumpage) {
      setTimeout(function() {
        wx.showLoading({
          title: '加载中',
          mask: true
        })
      }, 0)
      that.setData({
        nowpage: nowpage
      })
      that.getqingdan()
    } else {
      wx.showToast({
        title: '已经到底了',
        icon: 'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})